package com.yunhe.rentcars.pro.controller;

import com.yunhe.rentcars.commons.dto.JSONResponse;
import com.yunhe.rentcars.commons.util.ConfigUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author maliang
 * @version V1.0
 * @date 2017/11/14 0014 15:28
 * @Description: 文件和图片存储
 */
@Controller
@RequestMapping
public class StorageController {
    /**
     * 文件和图片上传
     * @param req
     * @return
     * @throws IOException
     * @throws ServletException
     */
    @RequestMapping("/upload")
    @ResponseBody
    public JSONResponse ul(HttpServletRequest req) throws IOException, ServletException {
        String path = ConfigUtils.readValue("fs.baseDir");   //  读取上传文件的根目录
        File uploadDir = new File(path);
        List<String> srcList = new ArrayList<>();
        if(!uploadDir.exists()){
            uploadDir.mkdirs();
        }
        // 上传多个文件
        Collection<Part> parts = req.getParts(); // 获取上传文件的集合
        for(Part part : parts){
            String submittedFileName = part.getSubmittedFileName();
            String suffix = submittedFileName.substring(submittedFileName.lastIndexOf("."));
            String fileName = System.currentTimeMillis() + suffix;
            if(!fileName.isEmpty()){
                part.write(uploadDir +  File.separator + fileName ); // 文件上传位置
                srcList.add(fileName);
            }
        }
        JSONResponse result = JSONResponse.success("上传成功！", srcList);
        return result;
    }

    /**
     * 文件下载 预览
     * @param req
     * @param resp
     * @throws IOException
     */
    @RequestMapping("/download")
    public void dl(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String path = ConfigUtils.readValue("fs.baseDir");   //  读取上传文件的根目录
        String fileName = req.getParameter("fileName");// 获取文件名
        File file = new File(path + fileName); // 获取文件
        if(file.exists()){
            byte[] bytes = new byte[1024*1024];
            InputStream fileInputStream = new FileInputStream(file);
            ServletOutputStream outputStream = resp.getOutputStream(); //获得输出流 进行下载
            int len;
            while ((len = fileInputStream.read(bytes)) != -1) {
                outputStream.write(bytes,0,len);
            }
            outputStream.flush();
            fileInputStream.close();
            outputStream.close();
        }
    }

    @RequestMapping("/download/file")
    public void dlFile(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String path = ConfigUtils.readValue("fs.baseDir");   //  读取上传文件的根目录
        String fileName = req.getParameter("fileName");// 获取文件名
        String dlName = req.getParameter("name");// 获取下载文件名
        File file = new File(path + fileName); // 获取文件
        String name = URLEncoder.encode(dlName, "utf-8"); // 防止中文乱码
        resp.setHeader("content-disposition","attachment;filename=" + name);// 让浏览器以附件的形式下载文件，并指定文件名称
        if(file.exists()){
            byte[] bytes = new byte[1024*1024];
            InputStream fileInputStream = new FileInputStream(file);
            ServletOutputStream outputStream = resp.getOutputStream(); //获得输出流 进行下载
            int len;
            while ((len = fileInputStream.read(bytes)) != -1) {
                outputStream.write(bytes,0,len);
            }
            outputStream.flush();
            fileInputStream.close();
            outputStream.close();
        }
    }
}
